package com.koomii.myproject.tx.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import com.koomii.myproject.dao.IdSequenceDao;
import com.koomii.myproject.domain.entity.IdSequence;
import com.koomii.myproject.tx.IdSequenceTx;
import com.koomii.common.tx.BaseTx;

@Service
public class IdSequenceTxImpl extends BaseTx  implements IdSequenceTx {
	
	@Autowired
	IdSequenceDao idSequenceDao;

	@Override
	public Integer getAndUpdateNextIdSequence(final String idKey,final Integer firstValue){
		
		TransactionTemplate template = getDataSourceTransactionManager();
        return (Integer)template.execute(new TransactionCallback<Object>() {
            @Override
            public Object doInTransaction(TransactionStatus transactionStatus) {
                try {
                	//1、根据idKey查询IdSequence
                	IdSequence idSequence = idSequenceDao.findByIdKeyForUpdate(idKey);
                	//2、有则+1更新
                	if(idSequence != null){
                		int value = idSequence.getValue();
                		idSequence.increaseValue();
                		idSequenceDao.update(idSequence);
                		return value;
                	}
                	//3、没有则创建保存
                	idSequence = new IdSequence();
                	idSequence.setIdKey(idKey);
                	idSequence.setValue(firstValue);
                	idSequenceDao.save(idSequence);
                    return firstValue;
                } catch (Exception e) {
                	transactionStatus.setRollbackOnly();
                    return 1;
                }
            }
        });
	}

}
